//
//  ShoppingCartViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/1/29.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import MJRefresh
import Alamofire
import PKHUD
import SwiftyJSON
import Networking

class ShoppingViewController: RootViewController, UICollectionViewDelegate, UICollectionViewDataSource, WCLWaterFallLayoutDelegate, GetRandomNumber, FalseData, CollectionWaterfallLayoutProtocol {
    
    private let bannerHeight: CGFloat = 211
    private let pageControlHeight: CGFloat = 25
    private let consultationHeight: CGFloat = 125
    private let headerViewHeight: CGFloat = 200
    
    lazy var bannerView: FSPagerView = {
        
        let bannerView = FSPagerView()
        bannerView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: kHeight(r: ConsultationViewController.bannerHeight))
        bannerView.delegate = self
        bannerView.dataSource = self
        bannerView.isInfinite = true
        bannerView.automaticSlidingInterval = 3.0
        bannerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        return bannerView
    }()
    lazy var pageControl: FSPageControl = {
        let pageControl = FSPageControl()
        pageControl.frame = CGRect(x: 0, y: bannerView.height - ConsultationViewController.pageControlHeight, width: bannerView.width, height: ConsultationViewController.pageControlHeight)
        pageControl.numberOfPages = bannerData.count
        pageControl.contentHorizontalAlignment = .center
        pageControl.contentInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        pageControl.setFillColor(.gray, for: .normal)
        pageControl.setFillColor(.white, for: .selected)
        pageControl.setPath(UIBezierPath.init(roundedRect: CGRect.init(x: 0, y: 0, width: 5, height: 5),                 cornerRadius: 2.5), for: .normal)
        pageControl.setPath(UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 5, height: 5)), for: .selected)
        pageControl.itemSpacing = 8
        return pageControl
    }()
    private var commodityModels: [GoodsModel] = []
    private var recommendData: [GoodsModel] = []
    var bannerData:[BannerModel] = []
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    var page:Int = 0
    var totalPage:Int = 0    
    var collectionView: UICollectionView!
    var waterfallLayout: CollectionWaterfallLayout?
    
    
    var heightArr: [CGFloat] = []
    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = ONColor.cellBGColor

        titleLabel(text: "购买", nil)

        setNavigationColor(colorState: .black)
        
        createCollectionView()
        initMainCollectionView()

        // Do any additional setup after loading the view.
    }
    func initMainCollectionView() {
//        collectionView.register(UINib(nibName: "\(ShoppingListCollectionViewCell.self)", bundle: nil), forCellWithReuseIdentifier: "shoppingcell")
        
        collectionView.register(ProductCollectionViewCell.self, forCellWithReuseIdentifier: "shoppingcell")
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "foot")
//
        let headerAction:Selector = #selector(headerRefresh)
        header.setRefreshingTarget(self, refreshingAction: headerAction)
        collectionView.mj_header = header
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        collectionView.mj_footer = footer
        collectionView.mj_footer.isHidden = true
        headerRefresh()
    }
    
    func createCollectionView() {
        
       let flowLayout = UICollectionViewFlowLayout();
        self.waterfallLayout = CollectionWaterfallLayout()
        self.waterfallLayout?.delegate = self
        self.waterfallLayout?.columns = 2
        self.waterfallLayout?.columnSpacing = 10
        self.waterfallLayout?.insets = UIEdgeInsetsMake(0, 10, 0, 10)
        self.collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight - 49 - 64), collectionViewLayout: flowLayout)
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.backgroundColor = UIColor.clear
        
        self.view.addSubview(self.collectionView)
        let layout = WCLWaterFallLayout.init(lineSpacing: 10, columnSpacing: 10, sectionInsets: UIEdgeInsetsMake(0, 10, 0, 10))
        layout.delegate = self
        collectionView.collectionViewLayout = layout
//        collectionView.collectionViewLayout = flowLayout
    }
    // MARK: - UICollectionViewDataSource
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print(commodityModels)
        return commodityModels.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "shoppingcell", for: indexPath) as? ProductCollectionViewCell
        return cell!
    }
   
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        let cell1:ProductCollectionViewCell  = cell as! ProductCollectionViewCell
        cell1.bindData(model: commodityModels[indexPath.row
            ])
    }
    //MARK: WCLWaterFallLayoutDelegate
    
    func collectionViewLayout(_ layout: CollectionWaterfallLayout!, heightForItemAt indexPath: IndexPath!) -> CGFloat {

        let height = self.heightArr[indexPath.row]
        return CGFloat(height)
    }
    func collectionViewLayout(_ layout: CollectionWaterfallLayout!, heightForSupplementaryViewAt indexPath: IndexPath!) -> CGFloat {
        return consultationHeight + bannerHeight + 60
    }
    
    func waterFall(_ collectionView: UICollectionView, layout waterFallLayout: WCLWaterFallLayout, heightForItemAt indexPath: IndexPath) -> CGFloat {
//        let model: GoodsModel = commodityModels[indexPath.row
//        ]
//        let height = ShoppingListCollectionViewCell.caculateHeight(model: model)
         let height = self.heightArr[indexPath.row]

        return CGFloat(height)
    }
    
    func columnOfWaterFall(_ collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func waterFall(_ collectionView: UICollectionView, layout waterFallLayout: WCLWaterFallLayout, heightForHeaderAt indexPath: IndexPath) -> CGFloat {
        return consultationHeight + bannerHeight + 60
    }
    func waterFall(_ collectionView: UICollectionView, layout waterFallLayout: WCLWaterFallLayout, heightForFooterAt indexPath: IndexPath) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionElementKindSectionHeader {
            
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header", for: indexPath)
            headerView.addSubview(setBannerData())
            headerView.addSubview(setConsultationCollectionView(arr: recommendData))
           
            return headerView
        } else {
            let foot = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "foot", for: indexPath)
            return foot
        }
    }

    // MARK: - collectionDelegate
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let shoppingDetailVC = ShoppingDetailViewController(nibName: "\(ShoppingDetailViewController.self)", bundle: nil)
        shoppingDetailVC.commodityModel = commodityModels[indexPath.row]
        self.navigationController?.pushViewController(shoppingDetailVC, animated: true)
    }
 
    // 顶部刷新
    @objc func headerRefresh(){
        print("下拉刷新") // 结束刷新
        page = 0
        self.footerRefresh()
        fetchBannerList(type: 4)
        fetchRecommendProductList()
    }
    // 底部刷新
    @objc func footerRefresh(){
        print("上拉刷新")
        page += 1
        self.fetchProductList(parameters: ["page":page,"pageSize":10,"keyword":""])
    }

    /// 获取banner数据
    func fetchBannerList(type:Int) -> Void {
        let requesturl = "\(BaseURL)\(bannerUlr)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: ["type":type] ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"].array!
                                        
                                        self.bannerData.removeAll()
                                        
                                        for subject in arr{
                                            
                                            let dic = subject.dictionary!
                                            let model = BannerModel(fromDic: dic)
                                            self.bannerData.append(model)
                                            
                                        }
                                        self.pageControl.numberOfPages = self.bannerData.count
                                        self.bannerView.reloadData()
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
    
    /// 获取推荐商品列表数据
    func fetchRecommendProductList() -> Void {
        let requesturl = "\(BaseURL)\(recommendShoppingListUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: nil ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        self.recommendData.removeAll()

                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            
                                            var model = GoodsModel(fromDic: dic)
                                            model.type = "4"
                                            self.recommendData.append(model)
                                        }
                                        
                                        self.collectionView.reloadData()
                                        
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
    /// 获取商品数据
    func fetchProductList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(shoppingListUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        print("===========")
                                        
                                        if self.page == 1{
                                            self.commodityModels.removeAll()
                                            self.collectionView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.collectionView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            var model = GoodsModel(fromDic: dic)
                                            let files = dic["fileInfos"]?.array
                                            if (files != nil){
                                                model.initFileInfos(arr: (dic["fileInfos"]?.array!)!)
                                            }
                                          
                                            model.initSpecifications(arr: (dic["specifications"]?.array!)!)
                                            model.initLabel(dic: (dic["label"]?.dictionary!)!)
                                            let height:CGFloat = ProductCollectionViewCell.caculateHeight(model: model)
                                            self.heightArr.append(height)
                                            self.commodityModels.append(model)
                                        }
                                        if self.totalPage == self.commodityModels.count{
                                            self.collectionView.mj_footer.isHidden = true
                                        }
                                        else{
                                            self.collectionView.mj_footer.isHidden = false
                                        }
                                        
                                        self.collectionView.reloadData()
                                    }
                                    else{
                                        if self.page == 1{
                                            self.collectionView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.collectionView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.collectionView.mj_header.endRefreshing()
                                }
                                else{
                                    self.collectionView.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }

}

extension ShoppingViewController: FSPagerViewDelegate, FSPagerViewDataSource, BottomShadow {
    
    func setBannerData() -> UIView {
        bannerView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: kHeight(r: bannerHeight))
        bannerView.delegate = self
        bannerView.dataSource = self
        bannerView.isInfinite = true
        bannerView.automaticSlidingInterval = 2
        bannerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        pageControl.frame = CGRect(x: 0, y: bannerView.height - pageControlHeight, width: bannerView.width, height: pageControlHeight)
        pageControl.numberOfPages = bannerData.count
        pageControl.contentHorizontalAlignment = .center
        pageControl.contentInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        pageControl.itemSpacing = 8
        
        let mainView = UIView()
        var rect = bannerView.frame
        rect.size.height += 10
        mainView.frame = rect
        mainView.backgroundColor = ONColor.cellBGColor
        mainView.addSubview(bannerView)
        mainView.addSubview(pageControl)
        setShadow(view: bannerView, opacity: 0.5, size: bottomShadowOffset, color: UIColor.black, cornerradius: 0)
        return mainView
    }
    
    func setConsultationCollectionView(arr:[GoodsModel]) -> UIView {
        let consultationCV: ConsultationCollectionView = ConsultationCollectionView()
        consultationCV.frame = CGRect(x: 0, y: bannerView.height + 10, width: ScreenWidth, height: consultationHeight)
        consultationCV.setData(arr: arr)
        consultationCV.delegateVc = self

        return consultationCV
    }
    
    // MARK:- FSPagerView DataSource
    
    public func numberOfItems(in pagerView: FSPagerView) -> Int {
        return bannerData.count
    }
    
    public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
        cell.isDescribeLabel = true
        cell.imageView?.contentMode = .scaleAspectFill
        cell.imageView?.clipsToBounds = true
        cell.textLabel?.font = UIFont.systemFont(ofSize: 15)
        
        let model = self.bannerData[index]
        if let cpath = model.image{
            let path:String = "\(BaseURL)\(cpath)"
            
            let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
            
            cell.imageView?.sd_setImage(with: url! as URL, completed: nil)
        }
        if let name = model.title{
            cell.textLabel?.text = name
        }

        return cell
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
        pagerView.scrollToItem(at: index, animated: true)
        self.pageControl.currentPage = index
        let model = self.bannerData[index]
        bannerJump(model: model)
    }
    
    func pagerViewDidScroll(_ pagerView: FSPagerView) {
        guard self.pageControl.currentPage != pagerView.currentIndex else {
            return
        }
        self.pageControl.currentPage = pagerView.currentIndex
    }
    
    
    @objc func returnRootVC() {
        self.navigationController?.popToRootViewController(animated: true)
    }
    
    
  
}
